package com.glodon.paas.test.util;

import java.util.concurrent.LinkedBlockingQueue;

import com.glodon.paas.util.TPS;

/**
 * @author a
 */
public class MultProcesser {

    private LinkedBlockingQueue<Runnable> queue;           // 任务队列
    private boolean                       closing = false; // 开始关闭，不接受新任务
    private boolean                       running = true; // 线程结束

    public MultProcesser(int nThreads) {
        this(nThreads, nThreads * 2);
    }

    public MultProcesser(int nThreads, int queueSize) {
        queue = new LinkedBlockingQueue<Runnable>(queueSize);

        // 创建nThreads个线程，并启动
        for (int i = 0; i < nThreads; i++) {
            Thread thread = new Thread() {

                public void run() {
                    while (running) {
                        try {
                            queue.take().run();
                        } catch (InterruptedException e) {
                            System.out.println("---->queue.take() error");
                            e.printStackTrace();
                        }
                    }
                }
            };
            thread.setDaemon(true);
            thread.start();
        }
    }

    /**
     * 提交任务
     * 
     * @param task
     * @throws InterruptedException
     */
    public void submit(Runnable task) {
        if (closing) {
            throw new RuntimeException("MultProcesser is closing");
        }
        try {
            queue.put(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 批量提交任务
     * 
     * @param task 任务
     * @param count 提交次数
     */
    public void submit(Runnable task, int count) {
        for (int i = 0; i < count; i++) {
            submit(task);
        }
        System.out.println("---->submit task :" + count);
    }

    public void shutdown() {
        closing = true;
        while (queue.size() > 0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        running = false;
        System.out.println("---->service is shutdowned");
    }

    public static void main(String[] args) {
        MultProcesser pro = new MultProcesser(10);
        final TPS tps = new TPS("test", 1);
        tps.start();

        Runnable task = new Runnable() {

            public void run() {
                String tname = Thread.currentThread().getName();
                tps.increment();
                System.out.println("------------------Thread:" + tname);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        };

        pro.submit(task, 100);
        pro.shutdown();
    }
}
